//
//  AesHelper.swift
//  TimeManager
//
//  Created by 清风徐来 on 2023/10/7.
//

import UIKit
import CryptoSwift

class AesHelper {

    /// AES加密
    /// - Parameters:
    ///   - str: 待加密字符
    ///   - aes_key: 加密Key
    /// - Returns: 加密后的字符
    class func aes_encrypt(_ str: String, aes_key: String = "AesHelper") -> String {
        var encryptedStr = ""
        do {
            // AES encrypt
            let encrypted = try AES(key: Array(aes_key.utf8), blockMode: ECB(), padding: .pkcs7).encrypt(str.bytes)
            let data = Data(base64Encoded: Data(encrypted), options: .ignoreUnknownCharacters)
            // 加密结果从data转成string 转换失败  返回""
            encryptedStr = String(bytes: data!.bytes, encoding: .utf8) ?? ""
        } catch {
            print(error.localizedDescription)
        }
        return encryptedStr
    }

    /// AES解密
    /// - Parameters:
    ///   - str: 待解密字符
    ///   - aes_key: 解密Key
    /// - Returns: 解密后的字符
    class func aes_decrypt(_ str: String , aes_key: String = "AesHelper") -> String {
        // decode base64
        let data = Data(base64Encoded: str, options: .ignoreUnknownCharacters)!
        var decrypted: [UInt8] = []
        do {
            // decode AES
            decrypted = try AES(key: Array(aes_key.utf8), blockMode: ECB(), padding: .pkcs7).decrypt(data.bytes)
        } catch {
            print(error.localizedDescription)
        }

        // 解密结果从data转成string 转换失败  返回""
        return String(bytes: Data(decrypted).bytes, encoding: .utf8) ?? ""
    }
}
